<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 * @version    $Id: Controller.php 2011-03-09 08:45:41Z idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 */

class Vote_Widget_ProfileParticipantController extends Engine_Content_Widget_Abstract
{
  
  public function indexAction()
  {
    // Don't render this if not authorized
    $viewer = Engine_Api::_()->user()->getViewer();
    if (!Engine_Api::_()->core()->hasSubject()) {
      return $this->setNoRender();
    }

    // Get subject and check auth
    $subject = Engine_Api::_()->core()->getSubject('vote_challenge');
    if (!$subject->authorization()->isAllowed($viewer, 'participate')) {
      return $this->setNoRender();
    }

    // Member type
    $this->view->subject = $subject = Engine_Api::_()->core()->getSubject();

    if ($subject->isFinished()) {
      return $this->setNoRender();
    }

    $formClass = 'Vote_Form_' . ucfirst($subject->type) . '_Participate';
    $this->view->form = $form = new $formClass();
    $this->view->justParticipated = false;
    $this->view->canVote = $subject->isStarted() && $subject->authorization()->isAllowed(null, 'vote');
    
    $controller = Zend_Controller_Front::getInstance();
    $request = $controller->getRequest();
    
    if ($request->isPost()) {
      $task = $request->getParam('task');
      if ($task == 'participate') {
        $values = $request->getPost();
        if ($form->isValid($values)) {
          if ($form->participate($subject)) {
            $this->view->justParticipated = true;
          }
        }
        $form->populate($values);
      }
    }

    $this->view->isPart = $isPart = $subject->isParticipated($viewer);
    if ($isPart) {
      $this->getElement()->setParam('Title', 'Your Info');
      $this->view->participant = $subject->getParticipantInfo($viewer);
    } else {
      $this->getElement()->setParam('Title', 'Participate');
      $this->view->participant = null;
    }
  }

}